#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import os
from pathlib import Path

import numpy as np
import tqdm
from PIL import Image
import cv2



def convert(input, output):
    cvimg =  cv2.imread(str(input))
    img = np.asarray(Image.open(input))
    assert img.dtype == np.uint8
    img = img - 1  # 0 (ignore) becomes 255. others are shifted by 1
    Image.fromarray(img).save(output)

os.environ['DETECTRON2_DATASETS'] = '/root/ws/data'

if __name__ == "__main__":
    dataset_dir = Path(os.getenv("DETECTRON2_DATASETS", "datasets")) / "uavid"
    for name in ["train_512", "val_512"]:
        annotation_dir = dataset_dir  / name / "masks_0"
        output_dir = dataset_dir /  name / "masks" 
        output_dir.mkdir(parents=True, exist_ok=True)
        for file in tqdm.tqdm(list(annotation_dir.iterdir())):
            output_file = output_dir / file.name
            convert(file, output_file)
